package src.origintrail;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;

/**
 * The shop action file
 * @author csmythe
 */
public class ModuleShop {
    private static boolean isRun = false;
    Shopkeeper seller;
    protected static JLabel[] quantities = new JLabel[new ShopItemList().getItems().size() + 1];
    protected static int totalCost;
    protected static int totalMass;
    protected static double trailBoost = 1.0 + OriginTrail.plr.getMap().distanceTraveled()/1000.0;
    private JLabel[] items = new JLabel[new ShopItemList().getItems().size() + 1];
    private JPanel[] iPanel = new JPanel[new ShopItemList().getItems().size() + 1];
    private JLabel[] costs = new JLabel[new ShopItemList().getItems().size() + 1];
    private JPanel[] cPanel = new JPanel[new ShopItemList().getItems().size() + 1];
    private JLabel[] weights = new JLabel[new ShopItemList().getItems().size() + 1];
    private JPanel[] wPanel = new JPanel[new ShopItemList().getItems().size() + 1];
    private JButton[] plusButton = new JButton[new ShopItemList().getItems().size()];
    private JButton[] minusButton = new JButton[new ShopItemList().getItems().size()];
    private JPanel[] lineItemPanel = new JPanel[new ShopItemList().getItems().size() + 1];
    private JPanel[] dummyItemPanel = new JPanel[new ShopItemList().getItems().size() + 1];
    private JPanel listPanel = new JPanel();
    private static JButton continueButton = new JButton("Purchase and leave");
    private JLabel greeting = new JLabel();
    private static JLabel warning = new JLabel();
    private static JLabel spending = new JLabel();
    private static JLabel massing = new JLabel();
    private static int[] nums;
    private static ArrayList<Item> itemsBought = new ArrayList<Item>();
    private static boolean isInitialized = false;
    
    /**
     * Constructor
     */
    public ModuleShop(){
        seller = new Shopkeeper(new ShopList().getName());
		OriginTrail.animPanel.setVisible(false);
		OriginTrail.infoPanel.setPreferredSize(new Dimension(700,200));
		OriginTrail.shopPanel.setPreferredSize(new Dimension(700,200));
                isRun = false;
    }
    
    /**
     * Runs the shop logic
     * @throws Exception May throw exceptions to a nonexistent class if mistakes are made in other files.
     */
    public void run() throws Exception{
        if(isInitialized)
            OriginTrail.shopPanel.removeAll();
        
        nums = new int[new ShopItemList().getItems().size()];
        
        isInitialized = true;
        OriginTrail.shopPanel.setLayout(new BoxLayout(OriginTrail.shopPanel, BoxLayout.Y_AXIS));
        infoSetup();
        OriginTrail.shopPanel.setVisible(true);
        OriginTrail.uiPanel.setVisible(false);
        
        for(int i = 0; i < new ShopItemList().getItems().size(); i++)
            itemsBought.add(((Item)Class.forName(new ShopItemList().itemClass(i)).newInstance()));
        for(int i = 0; i < nums.length; i++)
            nums[i] = 0;
        totalCost = 0;
        labeling();
        OriginTrail.otFrame.pack();
        /*while(!ready){
            System.out.print("");
            if(l.set){
                break;
            }
        }*/
    }
    
    private void SetUpShopList(){
        lineItemPanel[0] = new JPanel();
        dummyItemPanel[0] = new JPanel();
        lineItemPanel[0].setLayout(new BoxLayout(lineItemPanel[0],BoxLayout.X_AXIS));
        items[0] = new JLabel("Item Name");
        costs[0] = new JLabel("Price");
        weights[0] = new JLabel("Weight");
        quantities[0] = new JLabel("Quantity");
        quantities[0].setPreferredSize(new Dimension(48*3,20));
        
        iPanel[0] = new JPanel();
        iPanel[0].add(items[0]);
        iPanel[0].setPreferredSize(new Dimension(200, 20));
        cPanel[0] = new JPanel();
        cPanel[0].add(costs[0]);
        cPanel[0].setPreferredSize(new Dimension(75, 20));
        wPanel[0] = new JPanel();
        wPanel[0].add(weights[0]);
        wPanel[0].setPreferredSize(new Dimension(75, 20));
        
        listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.Y_AXIS));
        quantities[0].setHorizontalAlignment(SwingConstants.CENTER);
        
        lineItemPanel[0].add(iPanel[0]);
        lineItemPanel[0].add(cPanel[0]);
        lineItemPanel[0].add(wPanel[0]);
        lineItemPanel[0].add(quantities[0]);
        dummyItemPanel[0].add(lineItemPanel[0]);
        
        listPanel.add(dummyItemPanel[0]);
        
        for(int i = 1; i <= new ShopItemList().getItems().size(); i++){
            lineItemPanel[i] = new JPanel();
            dummyItemPanel[i] = new JPanel();
            lineItemPanel[i].setLayout(new BoxLayout(lineItemPanel[i],BoxLayout.X_AXIS));
            items[i] = new JLabel(new ShopItemList().itemString(i-1));
            iPanel[i] = new JPanel();
            iPanel[i].add(items[i]);
            iPanel[i].setPreferredSize(new Dimension(200, 20));
            costs[i] = new JLabel(new ShopItemList().itemVal(i-1) + "");
            cPanel[i] = new JPanel();
            cPanel[i].add(costs[i]);
            cPanel[i].setPreferredSize(new Dimension(75, 20));
            weights[i] = new JLabel(new ShopItemList().itemMass(i-1) + "");
            wPanel[i] = new JPanel();
            wPanel[i].add(weights[i]);
            wPanel[i].setPreferredSize(new Dimension(75, 20));
            minusButton[i-1] = new JButton("-");
            minusButton[i-1].setPreferredSize(new Dimension(48,20));
            if(new ShopItemList().itemString(i-1).equals("Food"))
                minusButton[i-1].addActionListener(new MinusListener(i, 50));
            else
                minusButton[i-1].addActionListener(new MinusListener(i, 1));
            
            quantities[i] = new JLabel(new Integer(0).toString());
            quantities[i].setPreferredSize(new Dimension(48, 20));
            quantities[i].setHorizontalAlignment(SwingConstants.CENTER);
            plusButton[i-1] = new JButton("+");
            plusButton[i-1].setPreferredSize(new Dimension(48,20));
            if(new ShopItemList().itemString(i-1).equals("Food"))
                plusButton[i-1].addActionListener(new PlusListener(i, 50));
            else
                plusButton[i-1].addActionListener(new PlusListener(i, 1));
            
            lineItemPanel[i].add(iPanel[i]);
            lineItemPanel[i].add(cPanel[i]);
            lineItemPanel[i].add(wPanel[i]);
            lineItemPanel[i].add(minusButton[i-1]);
            lineItemPanel[i].add(quantities[i]);
            lineItemPanel[i].add(plusButton[i-1]);
            dummyItemPanel[i].add(lineItemPanel[i]);
            listPanel.add(dummyItemPanel[i]);
        }
        OriginTrail.shopPanel.add(listPanel, BorderLayout.CENTER);
        
    }
    
    private void infoSetup(){
        greeting.setText("\nWelcome to my shop! My name is " + seller.getName() + ".");
        JPanel textPanel = new JPanel();
        textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.Y_AXIS));
        textPanel.add(greeting);
        textPanel.add(warning);
        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new BorderLayout());
        continueButton.addActionListener(new LeaveListener());
        infoPanel.add(continueButton, BorderLayout.SOUTH);
        infoPanel.add(spending, BorderLayout.NORTH);
        infoPanel.add(massing, BorderLayout.CENTER);
        
        OriginTrail.shopPanel.add(textPanel);
        SetUpShopList();
        OriginTrail.shopPanel.add(infoPanel);
    }
    
    protected static void labeling(){
        spending.setText("Spending: " + ModuleShop.totalCost + "/" + OriginTrail.plr.bags.find(new Money()).getStack() + ".");
        massing.setText("Wagon load: " + ModuleShop.totalMass + "/" + -1 * new Wagon().initialize(1).getWeight() + ".");
        String s = " ";
        if(totalCost > OriginTrail.plr.bags.find(new Money()).getStack()){
            continueButton.setEnabled(false);
            s += " That costs too much!";
        }
        if(totalMass > -new Wagon().initialize(1).getWeight()){
            continueButton.setEnabled(false);
            s += " That weighs too much!";
        }
        if(s.equalsIgnoreCase(" ")){
            continueButton.setEnabled(true);
        }
        warning.setText(s);
    }
    
    private class LeaveListener implements ActionListener{
        private boolean set=false;

        @Override
        public void actionPerformed(ActionEvent e) {
            if(!isRun){
                for(int i = 0; i < nums.length; i++)
                    itemsBought.get(i).initialize(nums[i]);
                EvtSpawner.instance.spawnBuyEvent(itemsBought);
                int size = itemsBought.size();
                for(int i = 0; i < size; i++)
                    itemsBought.remove(0);
                OriginTrail.shopPanel.setVisible(false);
                EvtSpawner.instance.spawnMoveEvent();
                for(int i = 0; i < size+1; i++)
                    try{
                        EvtSpawner.instance.getHandler().pop().activate();
                    }catch(Exception x){
                        x.printStackTrace();
                    }
                System.out.println("Exiting shop");
            }
            isRun = true;
        }
        
        public void reset(){
            set = false;
        }
        
    }

    private static class PlusListener implements ActionListener {
        int index;
        int mult;

        public PlusListener(int i, int m) {
            index = i;
            mult = m;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Integer newInt = new Integer((Integer.parseInt(ModuleShop.quantities[index].getText())+mult));
            ModuleShop.quantities[index].setText(newInt.toString());
            ModuleShop.totalCost += (int)(mult * new ShopItemList().itemVal(index-1) * trailBoost);
            ModuleShop.totalMass += mult * new ShopItemList().itemMass(index-1);
            ModuleShop.nums[index-1] = newInt;
            ModuleShop.labeling();
        }
    }
    
        private static class MinusListener implements ActionListener {
        int index;
        int mult;

        public MinusListener(int i, int m) {
            index = i;
            mult = m;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if(Integer.parseInt(ModuleShop.quantities[index].getText()) > 0){
                Integer newInt = new Integer((Integer.parseInt(ModuleShop.quantities[index].getText())-mult));
                ModuleShop.quantities[index].setText(newInt.toString());
                ModuleShop.totalCost -= (int)(mult * new ShopItemList().itemVal(index-1) * trailBoost);
                ModuleShop.totalMass -= mult * new ShopItemList().itemMass(index-1);
                ModuleShop.nums[index-1] = newInt;
            }
            ModuleShop.labeling();
        }
    }
}
